﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;


public partial class Runner
{
    public void GetPackagesPath()
    {
        var directoryInfo = new DirectoryInfo(ProjectPath);

        var tried = new List<string>();
        DirectoryInfo solutionDirectory;
        while (true)
        {
            if (directoryInfo.GetFiles("*.sln").Any())
            {
                solutionDirectory = directoryInfo;
                break;
            }

            tried.Add(directoryInfo.FullName);
            directoryInfo = directoryInfo.Parent;
            if (directoryInfo == null)
            {
                throw new ExpectedException("Could not find Solution path. Tried: " + string.Join(Environment.NewLine, tried));
            }
        }
        var nugetConfig = Path.Combine(solutionDirectory.FullName, "nuget.config");
        if (File.Exists(nugetConfig))
        {
            var value = XDocument.Load(nugetConfig).Root.Element("repositoryPath").Value;
            if (string.IsNullOrWhiteSpace(value))
            {
                throw new ExpectedException(string.Format("packagesDirectory in '{0}' is empty.", nugetConfig));
            }
            PackagesPath = Path.Combine(solutionDirectory.FullName, value);
            return;
        }
        PackagesPath = Path.Combine(solutionDirectory.FullName, "Packages");
    }
}